﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using jSLApp.Client.Workflow;
using jSLCore.Client.Presentation.BaseControl.DialogMessage;
using jSLCore.Client.Utility;
using Microsoft.Web.Media.SmoothStreaming;
using Telerik.Windows.Input;
using MouseButtonEventArgs = System.Windows.Input.MouseButtonEventArgs;
using MouseWheelEventArgs = System.Windows.Input.MouseWheelEventArgs;

namespace jSLApp.Client.Controls
{
    public partial class VRPlayer : UserControl
    {
        public readonly RadCustomPlayer player;
        private readonly Grid _grid2;

        private Timer _seekTimer;
        public VRPlayer(RadCustomPlayer customPlayer, Grid grid2):this()
        {
            player = customPlayer;
            _grid2 = grid2;

            grid.Children.Clear();
            player.MediaFailed += PlayerOnMediaFailed;
            player.MediaOpened += mediaOpened;
            player.MediaEnded+=PlayerOnMediaEnded;
            player.DownloadProgressChanged += PlayerOnDownloadProgressChanged;
            player.SeekCompleted += PlayerOnSeekCompleted;
            player.Loaded += player_Loaded;
            player.CurrentStateChanged+=PlayerOnCurrentStateChanged;
            StartTimer();

            Application.Current.Host.Content.FullScreenChanged += ContentOnFullScreenChanged;

            Mouse.AddMouseDownHandler(vBrush, mouse_Clicking);
            Mouse.AddMouseDownHandler(vBrush3, mouse_Clicking);
            Mouse.AddMouseDownHandler(this,clickOnControl);
            Mouse.AddMouseDownHandler(ControlPanel, clickOnPanel);
        }

        private void clickOnPanel(object sender, Telerik.Windows.Input.MouseButtonEventArgs e)
        {
            ShowPanel();
            e.Handled = true;
        }

        private void clickOnControl(object sender, Telerik.Windows.Input.MouseButtonEventArgs e)
        {
            ShowPanel();
            e.Handled = true;
        }

        private void mouse_Clicking(object sender, Telerik.Windows.Input.MouseButtonEventArgs mouseButtonEventArgs)
        {
            mouseButtonEventArgs.Handled = true;

            if(mouseButtonEventArgs.ClickCount==1)
            {
                TogglePlay();
            }
            else
            {
                GoFullScreen();
                TogglePlay();
            }
        }

        private void PlayerOnCurrentStateChanged(object sender, RoutedEventArgs routedEventArgs)
        {
            if(player.CurrentState==SmoothStreamingMediaElementState.Playing)
            {
                VisualStateManager.GoToState(this, "Playing", true);
            }
        }

        private void PlayerOnMediaEnded(object sender, RoutedEventArgs routedEventArgs)
        {
            //VisualStateManager.GoToState(this, "Ready", true);
            player.Position = player.StartPosition;
        }


        public VRPlayer()
        {
            InitializeComponent();
        }

        private void ShowPanel()
        {
            Cursor = Cursors.Arrow;
            VisualStateManager.GoToState(this, "ControlPanelVisible", true);
            VisualStateManager.GoToState(this, "ControlPanelHidden", true);
        }

        private void ContentOnFullScreenChanged(object sender, EventArgs eventArgs)
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
              
                controlPanelFullScreenPresenter.Width = Application.Current.Host.Content.
                    ActualWidth;
                controlPanelFullScreenPresenter.Height = Application.Current.Host.Content.
                    ActualHeight;
              
                _grid2.Children.Remove(this);
                controlPanelFullScreenPresenter.Children.Add(this);

                popup.IsOpen = true;

                Focus();
                ShowPanel();
            }
            else
            {
                controlPanelFullScreenPresenter.Children.Clear();
                _grid2.Children.Add(this);

                popup.IsOpen = false;
                ShowPanel();
            }
        }

        private void PlayerOnMediaFailed(object sender, ExceptionRoutedEventArgs exceptionRoutedEventArgs)
        {
            VisualStateManager.GoToState(this, "Failed", true);
        }

        private void StartTimer()
        {
            if (_seekTimer != null)
                StopTimer();
            _seekTimer = new Timer(changePosition, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
        }

        private void StopTimer()
        {
            if (_seekTimer != null) _seekTimer.Dispose();
            _seekTimer = null;
        }

        private void changePosition(object state)
        {
            Dispatcher.BeginInvoke(() =>
                                       {
                                           disableSeek = true;
                                               slider.Value = player.Position.TotalMilliseconds;
                                           disableSeek = false;
                                       });
        }

        private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!disableSeek)
            {
                //StopTimer();
                player.Position = TimeSpan.FromMilliseconds(e.NewValue);
                ShowPanel();
            }

            var currentTime = TimeSpan.FromMilliseconds(e.NewValue);
            curTimeTxt.Text = currentTime.ToString(@"hh\:mm\:ss");
            totalTimeTxt.Text = player.EndPosition.ToString(@"hh\:mm\:ss");

            if(ControlPanel.Opacity==0)
            {
                Cursor=Cursors.None;
            }


            if (player.VideoPlaybackTrack != null)
            {
                var bitrate = (double)player.VideoPlaybackTrack.Bitrate / (1024 * 1024);
             
                bpsTxt.Text = "Качество воспроизведения: "+bitrate.ToString().Substring(0, 3) + "Mbps";
            }
 
        }

        private bool disableSeek = false;


        private void PlayerOnSeekCompleted(object sender, SeekCompletedEventArgs seekCompletedEventArgs)
        {
            disableSeek = false;
            StartTimer();
        }

        private void PlayerOnDownloadProgressChanged(object sender, RoutedEventArgs routedEventArgs)
        {
            if (player.DownloadProgress == 1)
            {
                DownloadProgress.Visibility=Visibility.Collapsed;
            }
            else
            {
                DownloadProgress.Visibility = Visibility.Visible;
            }

            DownloadProgress.SkipValue = player.DownloadProgressOffset;
            DownloadProgress.Value = player.DownloadProgress;
            
        }

        private void mediaOpened(object sender, RoutedEventArgs e)
        {
            slider.IsMoveToPointEnabled = true;
            slider.Minimum = player.StartPosition.TotalMilliseconds;
            slider.Maximum = player.EndPosition.TotalMilliseconds;
            VisualStateManager.GoToState(this, "InProgress", true);
        }
        
        private void goFullScreen_Clicked(object sender, System.Windows.RoutedEventArgs e)
        {
            GoFullScreen();
        }

        private void GoFullScreen()
        {
            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
        }

        private void player_Loaded(object sender, RoutedEventArgs e)
        {
            vBrush2.SetSource(player.mediaElement);
        }

        

        private void playPause_Clicked(object sender, RoutedEventArgs e)
        {
            ShowPanel();
            TogglePlay();
        }

        public Uri CachedSource;
        public bool CachedIsStreamingSource;

        public void TogglePlay()
        {
            if (DataHelper.IsSourceReady(this))
            {
                if (player.CurrentState == SmoothStreamingMediaElementState.Paused)
                {
                    player.Play();
                    VisualStateManager.GoToState(this, "Playing", true);
                }
                else
                {
                    try
                    {
                        player.Pause();
                        VisualStateManager.GoToState(this, "Paused", true);
                    }
                    catch
                    {
                    }
                }
            }
            else
            {
                if(CachedSource!=null)
                {
                    if(CachedIsStreamingSource)
                    {
                        player.SmoothStreamingSource = CachedSource;
                    }
                    else
                    {
                        player.Source = CachedSource;
                    }
                }
            }
        }

      

        private void toggleVolume_Clicked(object sender, RoutedEventArgs e)
        {
            ShowPanel();
            VolumeChange();
        }

        private void VolumeChange(bool up=true,bool repeat=true)
        {
            if (up)
            {
                if (player.Volume == 1 )
                {
                    if (repeat)
                    player.Volume = 0;
                }
                else
                {
                    player.Volume += 0.5;
                }
            }
            else
            {
                if (player.Volume == 0 )
                {
                    if (repeat)
                    player.Volume = 1;
                }
                else
                {
                    player.Volume -= 0.5;
                }
            }

            if (player.Volume == 0)
            {
                VisualStateManager.GoToState(this, "Muted", true);
            }
            else if (player.Volume == 0.5)
            {
                VisualStateManager.GoToState(this, "HalfVolume", true);
            }
            else if (player.Volume == 1)
            {
                VisualStateManager.GoToState(this, "FullVolume", true);
            }
        }

        private void mouse_Moved(object sender, MouseEventArgs e)
        {
            ShowPanel();
        }

        private void key_Down(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Space:
                    {
                        ShowPanel();
                        TogglePlay();
                    }
                    break;
                    case
                        Key.Up:
                        ShowPanel();
                        VolumeChange(true,false);
                    break;
                    case Key.Down: ShowPanel(); 
                        VolumeChange(false,false);
                    break;

            }
        }

        private void mouse_Wheel(object sender, MouseWheelEventArgs e)
        {
            VolumeChange(e.Delta > 0, false);
        }
    }

    public class RadCustomPlayer : SmoothStreamingMediaElement
    {
        internal MediaElement mediaElement;

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            mediaElement = (MediaElement)GetTemplateChild("MediaElement");
        }
    }
}
